<template>
    <view>
        <!-- 公共组件-每个页面必须引入 -->
        <public-module></public-module>
        <wlk-navbar title="分类" navbarType='0' :isShowLeft="false" ></wlk-navbar>
        <view class="u-wrap">
            <view class="u-search-box" @click="jump('/pages/goods/search')">
                <u-search :showAction="false" disabled bgColor="#FFFFFF" height="36"></u-search>
            </view>
          <block v-if="!loading && $u.test.isEmpty(categoryBox)">
            <view class="not-data">
              <u-empty
                  :icon="uEmpty.search"
                  text="暂无分类"
              >
              </u-empty>
            </view>
          </block>
          <block v-else>
            <view class="u-menu-wrap">
              <scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop">
                <view v-for="(item,index) in categoryBox" :key="index" class="u-tab-item" :class="[current==index ? 'u-tab-item-active' : '']" @tap.stop="swichMenu(index)">
                  <text class="u-line-2">{{item.name}}</text>
                </view>
              </scroll-view>

              <scroll-view @scrolltolower="scrolltolower" scroll-y scroll-with-animation class="right-box u-flex-1" :scroll-top="scrollRightTop" @scroll="rightScroll">
                <view class="page-view">
                  <view>
                    <image :src="categoryBox[current]?categoryBox[current].image:''" class="br08"  mode="aspectFill"></image>
                  </view>
                  <view class="mt20 goods-list">
                    <view class="pd20 goods shadow br08 wlkflex mb20 justify-between align-start" @click="$Router.push('/pages/goods/detail?id='+item.id)" v-for="(item,index) in goodsList">
                      <image :src="item.images[0]" class="br08"  mode="aspectFill"></image>
                      <view class="info wlkflex wrap align-content-between">
                        <view class="wd100">
                          <view class="title u-line-1">{{item.title}}</view>
                        </view>
                        <view class="wd100 money wlkflex justify-between">
                          <view class="left">
                            <view class="vip wlkflex br04 overHidden">
                              <view class="name" :style="{backgroundColor: themeColor}">会员价</view>
                              <view class="vip_price"><text class="mr05">¥</text>{{item.vip_price}}</view>
                            </view>
                            <view class="price mt10"><text class="mr05">¥</text>{{item.price}}</view>
                          </view>
                          <view class="right wlkflex justify-center relative" :style="{backgroundColor: themeColor}" @tap.stop="goodsAdd(index)">
                            <image  src="/static/images/index/cart.png" mode="widthFix"></image>
                            <view class="badge" v-if="item.cartTotal>0">
                              <u-badge bgColor="#FF5904"  max="99" :value="item.cartTotal"></u-badge>
                            </view>
                          </view>
                        </view>
                      </view>
                    </view>
                  </view>
                  <view class="load-more">
                    <u-loadmore :status="loadStatus" :loading-text="loadingText"  :loadmore-text="loadmoreText" :nomore-text="nomoreText" dashed  line />
                  </view>
                </view>
              </scroll-view>
            </view>
          </block>
            <!-- tabbar占位高度 -->
            <view :style="{height: systemInfo.tabbarH+'px'}"></view>
        </view>
        <u-popup closeable :show="addShow" @close="addShow=false" round="20">
            <wlk-goods-add @editAddShow="setAddShow" :item="goodsList[choseGoodsIndex]"></wlk-goods-add>
        </u-popup>
        <wlk-tabbar :isFillHeight="false"></wlk-tabbar>
    </view>
</template>

<script>
    var num = 0;
    var dsq = null;
    var _self;
    import { cal } from '@/wlkutils/cal'
    import { mapGetters, mapMutations } from 'vuex';
    import { toUrl } from '@/wlkutils/tools';
    import base from '@/base.js';
    import share from "@/wlkutils/share";
    export default {
        computed:{
            ...mapGetters(['themeColor','uEmpty']),
        },
        data() {
            return {
                systemInfo:base.systemInfo,
                isPopup:false,
                categoryBox:[],//分类商品
                // current: 0,
                scrollTop:0,
                specGoodsData:{},//选择的规格数据
                // ***滑动联动所需参数***
                oldScrollTop: 0,
                current: 0, // 预设当前项的值
                menuHeight: 0, // 左边菜单的高度
                menuItemHeight: 0, // 左边菜单item的高度
                itemId: '', // 栏目右边scroll-view用于滚动的id
                menuItemPos: [],
                arr: [],
                scrollRightTop: 0, // 右边栏目scroll-view的滚动高度
                timer: null, // 定时器
                flag:false,//禁止current两次赋值
                flag2:true,//是否禁止右侧滑动
                c_id:'',//跳转的参数--定位分类id位置
                searchList:[],

                addShow:false,
                choseGoodsIndex:0,
                goodsList:[],
                page: 1,
                loadStatus:'loading',
                loadingText: '努力加载中',
                loadmoreText: '轻轻上拉',
                nomoreText: '实在没有了',
                loading:true,

            }
        },
        onLoad(e) {
            uni.hideTabBar();
            this.cartBottom = uni.$u.addUnit(50+this.systemInfo.tabbarPaddingB, 'px')
            _self = this;
            this.c_id = e.c_id;
            this.getCateList()
        },
        watch:{
            isLogin(val){
                this.initGoodsList();
            }
        },
        onReady() {
            this.getMenuItemTop()
        },
        onShow(){
            // #ifndef MP-ALIPAY
            num = 0;
            this.DSQ()
            // #endif
        },
        onShareAppMessage(res){
            return share.setShareInfo();
        },
        methods: {
            scrolltolower() {
                if(this.loadStatus == "nomore"){
                    return;
                }
                this.page++;
                this.getGoodsList();
            },
            jump(path){
                toUrl(path);
            },
            px2upx(n){
                return n/(uni.upx2px(n)/n);
            },
            getCateList() {
                uni.$u.http.post('category/getList', {
                }).then(res => {
                    _self.categoryBox = res.data.list;
                    _self.loading = false;
                    if(!uni.$u.test.isEmpty(_self.categoryBox)){
                      // _self.searchList = res.data.searchList;
                      // 如果有传分类c_id参数-滑动到对应的选项
                      if(_self.c_id){
                        _self.categoryBox.forEach((item,index)=>{
                          if(item.id == _self.c_id){
                            let time = 1000 //实际接口这里数字可以调小点
                            // 等待页面渲染完成
                            setTimeout(()=>{
                              if(index>=2){
                                _self.swichMenu(index-1)
                              }
                            },time)
                            setTimeout(()=>{
                              _self.swichMenu(index)
                            },time+200)
                          }
                        })
                      }else{
                        _self.getGoodsList()
                      }
                    }

                }).catch(err => {

                })

            },
            initGoodsList(){
                this.loadStatus = 'loading';
                this.page = 1;
                this.goodsList = [];
                _self.getGoodsList();
            },
            getGoodsList() {
                uni.$u.http.post('goods/getList', {
                    type:'category',
                    category_id:this.categoryBox[this.current].id,
                    page: this.page,
                }).then(res => {
                    if (res && res.data && res.data.rows) {
                        this.goodsList = this.goodsList.concat(res.data.rows);
                    }
                    this.loadStatus = res.data.rows.length < res.data.limit ? 'nomore' : 'loadmore';
                }).catch(res => {

                })
            },
            // 点击左边的栏目切换
            async swichMenu(index) {
                // #ifdef MP-ALIPAY
                if(index == this.current) return ;
                this.current = index;
                // 如果为0，意味着尚未初始化
                if(this.menuHeight == 0 || this.menuItemHeight == 0) {
                    await this.getElRect('menu-scroll-view', 'menuHeight');
                    await this.getElRect('u-tab-item', 'menuItemHeight');
                }
                // 将菜单菜单活动item垂直居中
                this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2;
                // #endif
                // #ifndef MP-ALIPAY
                if(this.arr.length == 0) {
                    await this.getMenuItemTop();
                }
                if (index == this.current) return;
                this.scrollRightTop = this.oldScrollTop;
                this.$nextTick(function(){
                    this.scrollRightTop = this.arr[index];
                    this.current = index;
                    this.flag = true
                    this.flag2 = false //禁止右侧滑动
                    this.leftMenuStatus(index);
                    num = 0
                })
                // #endif
            },
            DSQ(isClear){
                // 解决点击分类，左侧多次滚动
                dsq && clearInterval(dsq)
                dsq = setInterval(()=>{
                    num+=100
                    if(num>500){
                        this.flag2 = true
                    }
                },100)
            },
            // 获取一个目标元素的高度
            getElRect(elClass, dataVal) {
                new Promise((resolve, reject) => {
                    const query = uni.createSelectorQuery().in(this);
                    query.select('.' + elClass).fields({size: true},res => {
                        // 如果节点尚未生成，res值为null，循环调用执行
                        if(!res) {
                            setTimeout(() => {
                                this.getElRect(elClass);
                            }, 10);
                            return ;
                        }
                        this[dataVal] = res.height;
                    }).exec();
                })
            },
            // ***********************************************  微信小程序 S  *****************************************************************
            // 设置左边菜单的滚动状态
            async leftMenuStatus(index) {
                // #ifndef MP-ALIPAY
                if(this.flag){
                    this.current = index;
                    this.flag = false
                }
                // 如果为0，意味着尚未初始化
                if (this.menuHeight == 0 || this.menuItemHeight == 0) {
                    await this.getElRect('menu-scroll-view', 'menuHeight');
                    await this.getElRect('u-tab-item', 'menuItemHeight');
                }
                // 将菜单活动item垂直居中
                this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2;
                // #endif
                //获取分类商品
                _self.initGoodsList()
            },
            // 获取右边菜单每个item到顶部的距离
            getMenuItemTop() {
                // #ifndef MP-ALIPAY
                new Promise(resolve => {
                    let selectorQuery = uni.createSelectorQuery();
                    selectorQuery.selectAll('.class-item').boundingClientRect((rects) => {
                        // 如果节点尚未生成，rects值为[](因为用selectAll，所以返回的是数组)，循环调用执行
                        if(!rects.length) {
                            setTimeout(() => {
                                this.getMenuItemTop();
                            }, 10);
                            return ;
                        }
                        rects.forEach((rect) => {
                            // 这里减去rects[0].top，是因为第一项顶部可能不是贴到导航栏(比如有个搜索框的情况)
                            this.arr.push(rect.top - rects[0].top);
                            resolve();
                        })
                    }).exec()
                })
                // #endif
            },
            // 右边菜单滚动
            async rightScroll(e) {
                // #ifndef MP-ALIPAY
                if(this.flag2 && !this.flag){
                    this.oldScrollTop = e.detail.scrollTop;
                    if(this.arr.length == 0) {
                        await this.getMenuItemTop();
                    }
                    if(this.timer) return ;
                    if(!this.menuHeight) {
                        await this.getElRect('menu-scroll-view', 'menuHeight');
                    }
                    setTimeout(() => { // 节流
                        this.timer = null;
                        // scrollHeight为右边菜单垂直中点位置
                        let scrollHeight = e.detail.scrollTop + this.menuHeight / 2;
                        for (let i = 0; i < this.arr.length; i++) {
                            let height1 = this.arr[i];
                            let height2 = this.arr[i + 1];
                            // 如果不存在height2，意味着数据循环已经到了最后一个，设置左边菜单为最后一项即可
                            if (!height2 || scrollHeight >= height1 && scrollHeight < height2) {
                                this.flag = true
                                this.leftMenuStatus(i);
                                return ;
                            }
                        }
                    }, 10)
                }
                // #endif
            },
            // ***********************************************  微信小程序 E  *****************************************************************

            goodsAdd(index){
                this.choseGoodsIndex = index;
                this.addShow = true;
            },
            setAddShow(quantity){
                this.addShow = false;
                if(quantity>0){
                    this.goodsList[this.choseGoodsIndex].cartTotal = cal.jia(this.goodsList[this.choseGoodsIndex].cartTotal,quantity).valueOf();
                }
            },
        },

    }
</script>

<style lang="scss" scoped>
    .u-wrap {
        height: calc(100vh);
        /* #ifdef H5 */
        height: calc(100vh - var(--window-top));
        /* #endif */
        /* #ifndef APP-NVUE */
        display: flex;
        /* #endif */
        flex-direction: column;
    }
    .u-search-box {
        padding: 18rpx 30rpx;

    }
    .u-search-inner {
        background-color: #f5f5f5;
        border-radius: 100rpx;
        /* #ifndef APP-NVUE */
        display: flex;
        /* #endif */
        align-items: center;
        padding: 10rpx 16rpx;
    }
    .u-search-text {
        font-size: 26rpx;
        color: #999;
        margin-left: 10rpx;
    }

    .u-menu-wrap {
        flex: 1;
        /* #ifndef APP-NVUE */
        display: flex;
        /* #endif */
        overflow: hidden;
    }
    .u-tab-view {
        width: 160rpx;
        height: 100%;
    }
    .u-tab-item {
        width: 160rpx;
        // height: 110rpx;
        padding: 34rpx 24rpx;

        box-sizing: border-box;
        /* #ifndef APP-NVUE */
        display: flex;
        /* #endif */
        align-items: center;
        justify-content: center;
        font-size: $font-base;
        color: #666666;
        font-weight: 400;
        line-height: 1;
        position: relative;
        z-index: 10;
        text{
            line-height: 1.2;
        }
    }
    .u-tab-item-active {
        position: relative;
        z-index: 10;
        font-weight: 600;
        background: #fff;
        color: #333333;
    }
    .u-tab-item-active::before {
        content: "";
        position: absolute;
        z-index: 10;
        border-left: 5rpx solid $-wash-color;
        height: 40rpx;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
    }
    .u-tab-view {
        height: 100%;
    }
    .right-box {
        background-color: #FFFFFF;
    }
    .page-view {
        //  padding: 16rpx;
         padding: 30rpx;
        image{
            width: 100%;
            height: 200rpx;
        }
        .goods-list{
            .goods{
                background-color: #FFFFFF;
                image{
                    width: 150rpx;
                    height: 150rpx;
                    display: block;
                }
                .info{
                    width: 66%;
                    height: 150rpx;
                    .title{
                        font-size: $font-lt;
                        font-weight: bold;
                    }
                    .desc{
                        color: $uni-text-color-grey;
                        font-size: $font-sm;
                    }
                    .money{
                        font-size: $font-base;
                        .left{
                            .vip{
                                max-width: 280rpx;
                                background-color: $-wash-wait-color;
                                .name{
                                    font-size: $font-base;
                                    color: #FFE785;
                                    padding: 6rpx 10rpx;

                                }
                                .vip_price{
                                    padding: 6rpx 10rpx;
                                }
                            }
                            .price{
                                color: $-wash-price-color;
                            }
                        }
                        .right{
                            width:60rpx;
                            height:60rpx;
                            border-radius: 50%;
                            image{
                                width: 30rpx;
                                height: 30rpx;
                            }
                            .badge{
                                position: absolute;
                                top: -22rpx;
                                right: -15rpx;
                                border: 2px solid #FFFFFF;
                                border-radius: 15px;
                            }
                        }

                    }

                }

            }
        }
    }
    .class-item {
        // margin-bottom: 30rpx;
        background-color: #fff;
        padding: 24rpx 24rpx 0 24rpx;
        .item-box:after {content: "";
            width: 28%;
            margin-bottom: 30rpx;
        }
        .item-list{
            width: 28%;
            margin-bottom: 30rpx;
            image{
                height: 152rpx;
            }
            .item-list-title{
                text-align: center;
                font-size: $font-base;
            }
        }
    }
    .item-title {
        margin-bottom: 20rpx;
        text{
            font-size: $font-sm;
        }
    }
</style>
